package com.hxzy.dao.Impl;

import com.hxzy.bean.Discuss;
import com.hxzy.bean.Message;
import com.hxzy.bean.User;
import com.hxzy.dao.DiscussDao;
import com.hxzy.service.Impl.MessageServiceImpl;
import com.hxzy.service.Impl.UserServiceImpl;
import com.hxzy.service.MessageService;
import com.hxzy.service.UserService;
import com.hxzy.util.JdbcUtils;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class DiscussDaoImpl implements DiscussDao {
    @Override
    public int save(Discuss discuss) {
        String sql="INSERT INTO message_discuss (content,date,message_id,user_id)VALUES(?,?,?,?)";
        Object[] params={discuss.getContent(),discuss.getDate(),discuss.getMessage().getId(),discuss.getUser().getId()};
        return JdbcUtils.executeUpdate(sql,params);
    }

    @Override
    public int update(Discuss discuss) {
        return 0;
    }

    @Override
    public int remove(Integer integer) {
        return 0;
    }

    @Override
    public List<Discuss> queryAll() {
        String sql="SELECT id,content,date,message_id message,user_id `user` FROM message_discuss";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql);
        return list.stream().map(t ->getDiscuss(t)).collect(Collectors.toList());
    }

    @Override
    public Discuss findById(Integer integer) {
        String sql="SELECT id,content,date,message_id message,user_id `user` FROM message_discuss WHERE id=?";
        List<Map<String, Object>> list = JdbcUtils.executeQuery(sql, integer);
        Optional<Discuss> first = list.stream().map(t -> getDiscuss(t)).findFirst();
        return first.orElse(null);
    }

    private Discuss getDiscuss(Map<String, Object> t) {
        int id = ((Long) (t.get("id"))).intValue();
        String content = (String) t.get("content");
        Date tamp= (Date) t.get("date");
        Timestamp timestamp=new Timestamp(tamp.getTime());
        LocalDateTime time = timestamp.toLocalDateTime();
        int id_num1 = ((Long) (t.get("message"))).intValue();
        MessageService me = new MessageServiceImpl();
        Message message = me.findById(id_num1);
        int id_num2 = ((Long) (t.get("user"))).intValue();
        UserService service = new UserServiceImpl();
        User user = service.findById(id_num2);
        return new Discuss(id, content, time, message, user);
    }
}
